package com.stormrage.edu.ctrl.learn;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.learn.LeaTermServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduMajor;
import com.stormrage.entity.learn.LeaTerm;
import com.stormrage.entity.learn.req.LeaTermCreateReq;
import com.stormrage.entity.learn.req.LeaTermReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @Title: LeaTermCtrl.java
 * @Package com.stormrage.edu.ctrl.learn
 * @Description: 学期 Controller
 * @author www.stormragetech.com
 * @date 2016年4月13日
 * @version V1.0
 */
@Controller
@RequestMapping("/term")
public class LeaTermCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(LeaTermCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private LeaTermServ leaTermServ;

	@RequiresPermissions("term:create")
	@RequestMapping(value = "/create/{id}", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduMajor major = eduMajorServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("major", major);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "lea/term/create";

	}

	@RequiresPermissions("term:create")
	@RequestMapping(value = "/create/{id}", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, @RequestParam(value = "count", required = false) Integer count,
			LeaTermCreateReq entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			Integer index = leaTermServ.create(entity);
			errMsg = "提示信息：添加编号为【 " + index + " 】的学期成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加学期失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/term/list";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/term/list";

	}

	@RequiresPermissions("term:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			LeaTerm entity = leaTermServ.queryById(id);

			// ------------------ 验证是否可以修改 ------------------
//			if (entity.getApplyDateStart().compareTo(new Date()) <= 0) {
//
//				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "原密码错误",
//						StormrageTechException.ERR_APP, "【 LeaTermCtrl 】-【 Edit 】");
//
//				err = ErrorRep.instance(false, exception.getMessage());
//				redirect.addFlashAttribute("err", err);
//
//				return "redirect:/term/list";
//
//			}

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "lea/term/edit";

	}

	@RequiresPermissions("term:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, LeaTerm req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			leaTermServ.update(req);
			errMsg = "提示信息：修改编号为【 " + req.getId() + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/term/list";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/term/list";

	}

	@RequiresPermissions("term:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 验证是否可以修改 ------------------
			LeaTerm entity = leaTermServ.queryById(id);
			if (entity.getApplyDateStart().compareTo(new Date()) <= 0) {
				StormrageTechException.instance(ErrCons.CTRL_ERR, "学期已进入报名时间，不能删除", StormrageTechException.ERR_APP,
						"【 LeaTermCtrl 】-【 Delete 】");
				errMsg = "提示信息：编号为【 " + entity.getId() + " 】的学期已进入报名时间，不能删除";
				err = ErrorRep.instance(false, errMsg);
				redirect.addFlashAttribute("err", err);
				return "redirect:/term/list";
			}

			// ------------------ Ctrl操作 ------------------
			leaTermServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/term/list";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/term/list";

	}

	@RequiresPermissions("term:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, LeaTermReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaTermCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "lea/term/list";
	}

	@RequiresPermissions("term:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, LeaTermReq req) {

		logger.debug(" 【 Controller 】- 【 LeaTermCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = leaTermServ.queryRepList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaTermCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

}
